﻿/* ********************************************************************************
 * 名称：MngrBaseInfo_RepositoryService
 * 描述：系统用户表  仓储服务接口实现类（本类通过CodeSmith软件生成生成）
 * 创建人：HFL
 * 创建日期：2020-06-01 17:48:55
 * 修改人：
 * 修改日期：
 * *******************************************************************************/
using WPay.Domain.MainModule.Interface.RepositoryServices;
using WPay.Domain.Model.DTOs;
using WPay.Domain.Model.Entities;
using WPay.Infrastructure.Repository.Base;
using WPay.Infrastructure.Repository.DapperCore;
using WPay.Infrastructure.Unity;
using Dapper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Model.DTO;
using WPay.Infrastructure.EFCore;
using WPay.Domain;
using Model.PageModel;
using System.Linq;
using Model.DTO.Manager;

namespace WPay.Infrastructure.Repository.MainModule
{
    /// <summary>
    /// 系统用户表 仓储服务接口实现类
    /// </summary>
    public class MngrBaseInfo_RepositoryService : RepositoryBase, IMngrBaseInfo_RepositoryService
    {
        /// <summary>
        /// 查询SQL语句
        /// </summary>
        private readonly string querySql = @"select ID,LoginName,PassWord,NickName,State,CreateTime,IsDeleted,LastLoginIP,LastLoginTime,ThisLoginIP,ThisLoginTime,LoginNumber,CpnId,Tel,Email from MngrBaseInfo where 1=1";
        /// <summary>
        /// 查询数据条数SQL语句
        /// </summary>
        private readonly string queryCountSql = @"select count(1) from MngrBaseInfo where 1=1";
        /// <summary>
        /// 新增SQL语句
        /// </summary>
        private readonly string addSql = @"insert into MngrBaseInfo(ID,LoginName,PassWord,NickName,State,CreateTime,IsDeleted,LastLoginIP,LastLoginTime,ThisLoginIP,ThisLoginTime,LoginNumber,CpnId,Tel,Email) values (@ID,@LoginName,@PassWord,@NickName,@State,@CreateTime,@IsDeleted,@LastLoginIP,@LastLoginTime,@ThisLoginIP,@ThisLoginTime,@LoginNumber,@CpnId,@Tel,@Email)";
        /// <summary>
        /// 修改所有字段SQL语句
        /// </summary>
        private readonly string editSql = @"update MngrBaseInfo set LoginName=@LoginName,PassWord=@PassWord,NickName=@NickName,State=@State,CreateTime=@CreateTime,IsDeleted=@IsDeleted,LastLoginIP=@LastLoginIP,LastLoginTime=@LastLoginTime,ThisLoginIP=@ThisLoginIP,ThisLoginTime=@ThisLoginTime,LoginNumber=@LoginNumber,CpnId=@CpnId,Tel=@Tel,Email=@Email where 1=1";
        /// <summary>
        /// 表主键where条件SQL语句
        /// </summary>
        private readonly string whereByPrimaryKey = @" and ID=@ID";

        #region 由软件生成，禁止修改，若需要扩展，请在下方进行扩展

        /// <summary>
        /// 根据主键获取系统用户表资料信息
        /// </summary>
        /// <param name="_iD"></param>
        /// <returns>返回单个系统用户表数据实体</returns>
        public MngrBaseInfo Get(string _iD)
        {
            string sql = querySql + whereByPrimaryKey;
            DynamicParameters param = new DynamicParameters();
            param.Add("ID", _iD);
            return base.QueryBySql<MngrBaseInfo>(sql, param);

        }

        /// <summary>
        /// 获取所有记录
        /// </summary>
        /// <param name="_cpnID">企业代码</param>
        /// <returns>返回系统用户表数据集合</returns>
        public List<MngrBaseInfo> GetAll(string _cpnID)
        {
            return base.QueryListBySql<MngrBaseInfo>(querySql + " and CpnID=@CpnID", new { CpnID = _cpnID });
        }

        /// <summary>
        /// 获取所有记录
        /// </summary>
        /// <param name="_param">查询条件字典，其中key必须使用字段名</param>
        /// <returns>返回系统用户表数据集合</returns>
        public List<MngrBaseInfo> GetAll(Hashtable _param)
        {
            //查询SQL语句组装
            string sql = querySql + base.GetQueryConditions(_param);
            //封装参数
            DynamicParameters dynamicParam = new DynamicParameters();
            foreach (string key in _param.Keys)
            {
                dynamicParam.Add(key, _param[key]);
            }

            return base.QueryListBySql<MngrBaseInfo>(sql, dynamicParam);
        }

        /// <summary>
        /// 按照分页条件查询数据集
        /// </summary>
        /// <param name="_param">查询条件字典，其中key必须使用字段名</param>
        /// <param name="_pageIndex">查询页码，从1开始，必传</param>
        /// <param name="_pageSize">每页查询数据条数，必传</param>
        /// <param name="_sort">排序列名，若要降序请用列名+" DESC"，必传</param>
        /// <param name="_pageCount">返回总页码数</param>
        /// <param name="_dataCount">返回总数据条数</param>
        /// <returns>返回系统用户表数据集合</returns>
        public List<MngrBaseInfo> GetByPage(Hashtable _param, int _pageIndex, int _pageSize, string _sort, out int _pageCount, out int _dataCount)
        {
            if (_pageIndex == 0 || _pageSize == 0 || string.IsNullOrWhiteSpace(_sort))
            {
                _dataCount = 0;
                _pageCount = 0;
                return null;
            }
            //封装参数
            DynamicParameters dynamicParam = new DynamicParameters();
            foreach (string key in _param.Keys)
                dynamicParam.Add(key, _param[key]);
            //组装计数sql语句
            string countSql = queryCountSql + base.GetQueryConditions(_param);
            _dataCount = base.QueryScalarBySql<Int32>(countSql, dynamicParam);//获取总数据条数
            _pageCount = (_dataCount + _pageSize - 1) / _pageSize;//总页数 =  (数据总条数 + 每页显示条数 - 1) / 每页显示条数
            if (_dataCount == 0)
            {
                return new List<MngrBaseInfo>();
            }
            //组装分页查询语句
            string sql = querySql + base.GetQueryConditions(_param, _pageIndex, _pageSize, _sort);

            return base.QueryListBySql<MngrBaseInfo>(sql, dynamicParam);
        }

        /// <summary>
        /// 插入系统用户表数据
        /// </summary>
        /// <param name="_mngrBaseInfo">需要插入的系统用户表数据实体</param>
        /// <returns>返回影响数据行数</returns>
        public int Add(MngrBaseInfo _mngrBaseInfo)
        {
            return base.ExecuteBySql(addSql, _mngrBaseInfo);
        }

        /// <summary>
        /// 批量插入系统用户表数据
        /// </summary>
        /// <param name="_mngrBaseInfoList">需要插入的系统用户表数据集合</param>
        /// <returns>返回影响数据行数</returns>
        public int Add(List<MngrBaseInfo> _mngrBaseInfoList)
        {
            return base.BulkInsert(_mngrBaseInfoList);
        }

        /// <summary>
        /// 根据主键更新系统用户表数据
        /// </summary>
        /// <param name="_mngrBaseInfo">需要更新的系统用户表数据实体</param>
        /// <returns>返回影响数据行数</returns>
        public int Update(MngrBaseInfo _mngrBaseInfo)
        {
            return base.ExecuteBySql(editSql + whereByPrimaryKey, _mngrBaseInfo);
        }

        /// <summary>
        /// 根据主键更新系统用户表指定字段
        /// </summary>
        /// <param name="_mngrBaseInfo">需要更新的系统用户表数据实体</param>
        /// <param name="_updateProNames">需要更新的字段名</param>
        /// <returns>返回影响数据行数</returns>
        public int Update(MngrBaseInfo _mngrBaseInfo, params string[] _updateProNames)
        {
            string sql = @"update MngrBaseInfo set ";
            sql += base.GetUpdateSet(_updateProNames);
            return base.ExecuteBySql(sql + whereByPrimaryKey, _mngrBaseInfo);
        }

        #endregion

        private readonly IEfCore_RepositoryService _efCore_RepositoryService;
        private Entities db;
        public MngrBaseInfo_RepositoryService(IEfCore_RepositoryService efCore_RepositoryService)
        {
            _efCore_RepositoryService = efCore_RepositoryService;
            db = _efCore_RepositoryService.DbContext();
        }
        /*业务扩展代码*/
        #region 业务扩展代码
        public EntityList<BaseInfoDTO> GetManagerList(int page, int rows, LoginUserDTO data, MangerUserParms mangerUserParms)
        {
            Dictionary<string, string> sort = new Dictionary<string, string>() { { "LastLoginTime", "DESC" } };
            var dbset = db.Set<MngrBaseInfo>();
            var wheresrole = PredicateBuilder.True<MngrRole>();
            var memrole = PredicateBuilder.True<MngrRole>();
            var whereMngrBaseInfo = PredicateBuilder.True<MngrBaseInfo>();
            if (data.CpnId == "system")
            {
                
                if (!string.IsNullOrEmpty(mangerUserParms.CpnId))
                {
                    whereMngrBaseInfo = whereMngrBaseInfo.And(x => x.CpnId == mangerUserParms.CpnId);

                }
            }
            else
            {
                whereMngrBaseInfo = whereMngrBaseInfo.And(x => x.CpnId == data.CpnId);
            }
            if (!string.IsNullOrEmpty(mangerUserParms.RoleId) && mangerUserParms.RoleId != null)
            {
                wheresrole = wheresrole.And(x => x.RoleId == mangerUserParms.RoleId);
            }
            if (!string.IsNullOrEmpty(mangerUserParms.Name))
            {
                whereMngrBaseInfo = whereMngrBaseInfo.And(x => x.LoginName.Contains(mangerUserParms.Name) || x.NickName.Contains(mangerUserParms.Name));
            }
            wheresrole = wheresrole.And(x => x.IsDeleted == mangerUserParms.IsDelete);
            whereMngrBaseInfo = whereMngrBaseInfo.And(x => x.IsDeleted == mangerUserParms.IsDelete);
            memrole= memrole.And(x => x.IsDeleted == mangerUserParms.IsDelete);
            var query = (from a in db.MngrBaseInfo.AsQueryable().Where(whereMngrBaseInfo)
                         join r in db.MngrRole.AsQueryable().Where(wheresrole) on a.ID equals r.MemberId
                         join cpn in db.Cpn.AsQueryable() on a.CpnId equals cpn.CpnID
                         group new { a.ID, a.LoginName, a.NickName, a.State, a.CreateTime, a.LastLoginTime, a.LastLoginIP, a.ThisLoginTime, a.ThisLoginIP, a.LoginNumber, a.CpnId, cpn.Name }
                         by a.ID into tb
                         select new BaseInfoDTO()
                         {
                             ID = tb.Key,
                             LoginName = tb.Max(x=>x.LoginName),
                             NickName = tb.Max(x => x.NickName),
                             State = tb.Max(x => x.State),
                             CreateTime = tb.Max(x => x.CreateTime),
                             LastLoginTime = tb.Max(x => x.LastLoginTime),
                             LastLoginIP = tb.Max(x => x.LastLoginIP),
                             ThisLoginTime = tb.Max(x => x.ThisLoginTime),
                             ThisLoginIP = tb.Max(x => x.ThisLoginIP),
                             LoginNumber = tb.Max(x => x.LoginNumber),
                             CpnId = tb.Max(x => x.CpnId),
                             CpnIDStr = tb.Max(x => x.Name),
                         });
            var result = _efCore_RepositoryService.FindAllAsQuery<BaseInfoDTO>(_efCore_RepositoryService.DataSort(query, sort), page, rows);
            var memberids = result.Data.Select(x => x.ID).Distinct().ToList();
            var l = (from r in db.MngrRole.Where(x => memberids.Contains(x.MemberId)).Where(memrole)
                     join role in db.SysRole on r.RoleId equals role.ID into temp2
                     from role1 in temp2.DefaultIfEmpty()
                     select new MngrRole()
                     {
                         ID = role1.RoleName,
                         RoleId = role1.ID,
                         MemberId = r.MemberId
                     }).ToList();
            result.Data.ForEach(x =>
            {
                var mr = l.Where(a => a.MemberId == x.ID).ToList();
                x.MangerRoles = string.Join(",", mr.Select(x => x.ID).Distinct());
                x.MangerRolesIDs = string.Join(",", mr.Select(x => x.RoleId).Distinct());
                x.MangerRoleId = l.Select(a => a.RoleId).Distinct();
                x.LastLoginTimeStr = x.LastLoginTime != null ? x.LastLoginTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
            });
            return result;

        }
        /// <summary>
        /// 获取所有账户
        /// </summary>
        /// <param name="data"></param>
        /// <param name="mangerUserParms"></param>
        /// <returns></returns>
        public List<BaseInfoDTO> GetManagerAll(LoginUserDTO data, MangerUserParms mangerUserParms)
        {
            Dictionary<string, string> sort = new Dictionary<string, string>() { { "LastLoginTime", "DESC" } };
            var wheres = PredicateBuilder.True<BaseInfoDTO>();
            var dbset = db.Set<MngrBaseInfo>();
            var wheresrole = PredicateBuilder.True<MngrRole>();
            var whereMngrBaseInfo = PredicateBuilder.True<MngrBaseInfo>();
            if (data.CpnId != "system")
            {
                wheres = wheres.And(x => x.CpnId == data.CpnId);
            }
            if (!string.IsNullOrEmpty(mangerUserParms.RoleId) && mangerUserParms.RoleId != null)
            {
                var id = mangerUserParms.RoleId;
                wheresrole = wheresrole.And(x => x.RoleId == mangerUserParms.RoleId);
            }
            if (!string.IsNullOrEmpty(mangerUserParms.Name))
            {
                wheres = wheres.And(x => x.LoginName.Contains(mangerUserParms.Name) || x.NickName.Contains(mangerUserParms.Name));
            }
            wheresrole = wheresrole.And(x => x.IsDeleted == mangerUserParms.IsDelete);
            whereMngrBaseInfo = whereMngrBaseInfo.And(x => x.IsDeleted == mangerUserParms.IsDelete);
            var query = (from a in db.MngrBaseInfo.Where(whereMngrBaseInfo)
                         join r in db.MngrRole.Where(wheresrole) on a.ID equals r.MemberId
                         join cpn in db.Cpn on a.CpnId equals cpn.CpnID into temp
                         from cpn1 in temp.DefaultIfEmpty()
                         select new BaseInfoDTO()
                         {
                             ID = a.ID,
                             LoginName = a.LoginName,
                             NickName = a.NickName,
                             State = a.State,
                             CreateTime = a.CreateTime,
                             LastLoginTime = a.LastLoginTime,
                             LastLoginIP = a.LastLoginIP,
                             ThisLoginTime = a.ThisLoginTime,
                             ThisLoginIP = a.ThisLoginIP,
                             LoginNumber = a.LoginNumber,
                             CpnId = a.CpnId,
                             CpnIDStr = cpn1 == null ? "" : cpn1.Name,
                             MangerRoles = null,
                             MangerRoleId = null,
                         }).Where(wheres);
            var result = query.ToList();
            var memberids = result.Select(x => x.ID).Distinct().ToList();
            var l = (from r in db.MngrRole.Where(x => !x.IsDeleted && memberids.Contains(x.MemberId))
                     join role in db.SysRole on r.RoleId equals role.ID into temp2
                     from role1 in temp2.DefaultIfEmpty()
                     select new MngrRole()
                     {
                         ID = role1.RoleName,
                         RoleId = role1.ID,
                         MemberId = r.MemberId
                     }).ToList();
            result.ForEach(x =>
            {
                var mr = l.Where(a => a.MemberId == x.ID).ToList();
                x.MangerRoles = string.Join(",", mr.Select(x => x.ID));
                x.MangerRolesIDs = string.Join(",", mr.Select(x => x.RoleId));
                x.MangerRoleId = l.AsQueryable().Where(wheresrole).Select(a => a.RoleId);
                x.LastLoginTimeStr = x.LastLoginTime != null ? x.LastLoginTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
            });
            return result;

        }
        public LoginUserDTO GetCaheUser()
        {
            var httpContext = MvcContext.GetContext();
            var tokenStr = httpContext.Request.Headers["Authorization"];
            TokenModel tm = RayPIMemoryCache.Get<TokenModel>(tokenStr);
            var dto = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginUserDTO>(tm.UserJson);
            if (dto == null)
            {
                dto = new LoginUserDTO();
                dto.DefActionList = new List<RoleAction_ModuleDTO>();
                dto.UserActionList = new List<RoleActionDTO>();
            }
            return dto;
        }
        #endregion
    }
}
